//
//  XVCAppointMentExhibitor.m
//  ppkc2016
//
//  Created by 拼凑的断音 on 16/4/8.
//  Copyright © 2016年 拼凑的断音. All rights reserved.
//

#import "XVCAppointMentExhibitor.h"
#import "XXTool.h"
#import "XVVTextViewWithPlaceholder.h"

@interface XVCAppointMentExhibitor ()

@property (nonatomic,strong) UITextField* selectTime;

@property (nonatomic,strong) UIDatePicker *datePicker;

@property (nonatomic,strong) XVVTextViewWithPlaceholder *inputRemarks;

@property (nonatomic,strong) NSArray *orderUsedTimeArray;

@end

@implementation XVCAppointMentExhibitor
-(UITextField*)selectTime
{
    if (_selectTime==nil)
    {
        //textview编辑完成
        UIToolbar * topView = [[UIToolbar alloc] initWithFrame:CGRectMake(0, 0, [UIScreen mainScreen].bounds.size.width, 30)];
        topView.backgroundColor = [XXTool colorWithBackGround];
        [topView setBarStyle:UIBarStyleDefault];
        UIBarButtonItem * btnSpace = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:self action:nil];
        
        UIButton *cancelBar=[[UIButton alloc] initWithFrame:CGRectMake(0, 0, 60, 30)];
        [cancelBar setTitle:NSLocalizedString(@"取消", nil) forState:UIControlStateNormal];
        
        cancelBar.titleLabel.font=[UIFont boldSystemFontOfSize:17];
        [cancelBar setTintColor:[XXTool colorWithProject]];
        [cancelBar setTitleColor:[XXTool colorWithProject] forState:UIControlStateNormal];
        [cancelBar addTarget:self action:@selector(clickTextFieldCancel) forControlEvents:UIControlEventTouchUpInside];
        
        UIBarButtonItem * cancelButton = [[UIBarButtonItem alloc] initWithCustomView:cancelBar];

        UIButton *attentionBar=[[UIButton alloc] initWithFrame:CGRectMake(0, 0, 80, 30)];
        [attentionBar setTitle:NSLocalizedString(@"完成", nil) forState:UIControlStateNormal];
        
        attentionBar.titleLabel.font=[UIFont boldSystemFontOfSize:17];
        [attentionBar setTintColor:[XXTool colorWithProject]];
        [attentionBar setTitleColor:[XXTool colorWithProject] forState:UIControlStateNormal];
        [attentionBar addTarget:self action:@selector(clickTextFieldDone) forControlEvents:UIControlEventTouchUpInside];
        
        UIBarButtonItem *doneButton=[[UIBarButtonItem alloc] initWithCustomView:attentionBar];
        // 根据中英文设置 宽度
        if ([XXTool didCurrentLanguageChinese])
        {
            cancelBar.frame=CGRectMake(0, 0, 40, 30);
            attentionBar.frame=CGRectMake(0, 0, 40, 30);
        }else{
            cancelBar.frame=CGRectMake(0, 0, 60, 30);
            attentionBar.frame=CGRectMake(0, 0, 80, 30);
        }
        
        NSArray * buttonsArray = [NSArray arrayWithObjects:cancelButton, btnSpace, doneButton, nil];
        
        [topView setItems:buttonsArray];
        
        
        UIView *leftView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 15, 5)];
        _selectTime = [[UITextField alloc] init];
        _selectTime.placeholder = NSLocalizedString(@"请选择预约时间", nil);
        _selectTime.backgroundColor = [UIColor whiteColor];
        _selectTime.leftView = leftView;
        _selectTime.leftViewMode = UITextFieldViewModeAlways;
        _selectTime.font = [XXTool systemFontOfSize:16];
        [_selectTime setValue:[XXTool colorWithHexString:@"8B8B8B"]
                         forKeyPath:@"_placeholderLabel.textColor"];
        [self.view addSubview:_selectTime];
        
        _selectTime.inputView = self.datePicker;
        [_selectTime setInputAccessoryView:topView];
    }
    return _selectTime;
}

-(UIDatePicker*)datePicker
{
    if (_datePicker==nil)
    {
       
        
        NSDate* minDate = [[NSDate alloc] initWithTimeIntervalSinceNow:0];
        
        
        NSCalendar  * cal=[NSCalendar  currentCalendar];
        NSUInteger  unitFlags=NSDayCalendarUnit|NSMonthCalendarUnit|NSYearCalendarUnit;
        NSDateComponents * conponent= [cal components:unitFlags fromDate:minDate];
        NSInteger year=[conponent year];
        
        NSString *maxDataString = [NSString stringWithFormat:@"%ld-12-31 23:59:59",(long)year];
        NSDateFormatter* formater = [[NSDateFormatter alloc] init];
        [formater setDateFormat:@"YYYY-MM-dd HH:mm:ss"];
        NSLocale* local =[[NSLocale alloc] initWithLocaleIdentifier:@"en_US"];
        [formater setLocale: local];
        
        NSDate* maxDate = [formater dateFromString:maxDataString];
         
        _datePicker = [[UIDatePicker alloc] init];
        _datePicker.backgroundColor = [UIColor whiteColor];
        _datePicker.datePickerMode = UIDatePickerModeDateAndTime;
        _datePicker.minimumDate = minDate;
        _datePicker.maximumDate = maxDate;
    }
    return _datePicker;
}

-(XVVTextViewWithPlaceholder*)inputRemarks
{
    if (_inputRemarks==nil)
    {
        _inputRemarks = [[XVVTextViewWithPlaceholder alloc] init];
        _inputRemarks.textFont = [XXTool systemFontOfSize:16];
        _inputRemarks.placeholder_textColor = [XXTool colorWithHexString:@"8B8B8B"];
        _inputRemarks.placeholder = NSLocalizedString(@"需要发送的留言信息", nil);
        _inputRemarks.backgroundColor =[UIColor whiteColor];
        [self.view addSubview:_inputRemarks];
    }
    return _inputRemarks;
}

-(void)initData
{
    [DKHTTPRequest sendDataWithShortUrl:@"electronic_catalogue_visitor_ordertime"
                                  Param:[XXTool formatStringWithLanguage:[NSString stringWithFormat:@"userid=%@&passwd=%@",[UserInfo shareUserInfo].userID,[UserInfo shareUserInfo].userPassword]]
                             ImageArray:nil
                                TimeOut:10
                             Completion:^BOOL(NSMutableDictionary *serverDic, DKHTTPResponseType bufferType) {
                                 if ([[serverDic objectForKey:@"code"] intValue]==200)
                                 {
                                     _orderUsedTimeArray = [serverDic objectForKey:@"zslist"];
                                     
                                 }
                                 return YES;
                             } IsBuffering:NO
                      IsNeedReplaceWrap:NO
                        IsUseUpLoadHead:NO];
}

-(void)initUI
{
    [self.navigationItem setTitle:NSLocalizedString(@"预约展商", nil)];
    self.view.backgroundColor = [XXTool colorWithBackGround];
    [self.navigationItem setRightBarButtonItem:[[UIBarButtonItem alloc] initWithTitle:NSLocalizedString(@"提交", nil) style:UIBarButtonItemStylePlain target:self action:@selector(clickSubmitAppointment)]];
    
    [self selectTime];
    [self inputRemarks];
}

-(void)refreshLayout:(CGRect)frame
{
    _selectTime.frame = CGRectMake(0, 30
                                   , frame.size.width
                                   , 54);
    _inputRemarks.frame = CGRectMake(0
                                     , _selectTime.frame.size.height+_selectTime.frame.origin.y+30
                                     , frame.size.width
                                     , frame.size.height-(_selectTime.frame.size.height+_selectTime.frame.origin.y+30));
}

-(void)clickTextFieldCancel
{
    [_selectTime resignFirstResponder];
    [_inputRemarks.inputView resignFirstResponder];
}

-(void)clickTextFieldDone
{
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    formatter.dateFormat = @"yyyy-MM-dd HH:mm";
    NSString *dateString = [formatter stringFromDate:_datePicker.date];
    _selectTime.text = dateString;
    [_selectTime resignFirstResponder];
}

-(void)clickSubmitAppointment
{
    if ([[UserInfo shareUserInfo].userName isEqualToString:@""])
    {
        [SVProgressHUD showInfoWithStatus:NSLocalizedString(@"请完善您的个人信息，以便于展商联系您", nil)];
        return;
    }
    if ([_selectTime.text isEqualToString:@""])
    {
        [SVProgressHUD showInfoWithStatus:NSLocalizedString(@"请选择预约时间", nil)];
        return;
    }
    if ([[_inputRemarks inputTextString] isEqualToString:@""])
    {
        [SVProgressHUD showInfoWithStatus:NSLocalizedString(@"请输入预约留言", nil)];
        return;
    }
    if ([_inputRemarks inputTextString].length>300)
    {
        [SVProgressHUD showInfoWithStatus:NSLocalizedString(@"预约留言必须在300字符内", nil)];
        return;
    }
    BOOL isRepeatTime = NO;
    if (_orderUsedTimeArray)
    {
        for (int i=0; i<_orderUsedTimeArray.count; i++)
        {
            if ([[NSString stringWithFormat:@"%@",_orderUsedTimeArray[i]] isEqualToString:[XXTool timeToStamp:_selectTime.text]])
            {
                isRepeatTime = YES;
            }
        }
    }
    if (isRepeatTime)
    {
        [SVProgressHUD showInfoWithStatus:NSLocalizedString(@"重复的预约时间,请选择其他时间", nil)];
        return;
    }
    
    [DKHTTPRequest sendDataWithShortUrl:@"electronic_catalogue_exhibitors_order"
                                  Param:[XXTool formatStringWithLanguage:[NSString stringWithFormat:@"userid=%@&vs_orderid=%@&order_time=%@&order_msg=%@",[UserInfo shareUserInfo].userID,_nowEXId,[XXTool timeToStamp:_selectTime.text],[_inputRemarks inputTextString]]]
                                                              ImageArray:nil
                                                                 TimeOut:10
                                                              Completion:^BOOL(NSMutableDictionary *serverDic, DKHTTPResponseType bufferType) {
                                                                  if ([[serverDic objectForKey:@"code"] intValue]==200)
                                                                  {
                                                                      [SVProgressHUD showSuccessWithStatus:NSLocalizedString(@"预约成功", nil)];
                                                                      [self.navigationController popViewControllerAnimated:YES];
                                                                  }
                                                                  return YES;
                                                              } IsBuffering:NO
                                                       IsNeedReplaceWrap:NO
                                                         IsUseUpLoadHead:NO];
}

#pragma mark api
+(void)pushAppointMentExhibitorWithSourceVC:(UIViewController *)sourceVC exhibitorId:(NSString *)exID
{
    XVCAppointMentExhibitor *vc = [[XVCAppointMentExhibitor alloc] init];
    vc.nowEXId = exID;
    if (sourceVC)
    {
        [sourceVC.navigationController pushViewController:vc animated:YES];
    }
}

@end
